package com.sms.client.utils;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.Base64.Decoder;
import java.util.Base64.Encoder;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;

/**
 * @desc RSA公钥加密/私钥解密
 * 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式<br/>
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密，<br/>
 * 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 * @author wjw
 * @time 2017年10月30日下午3:18:08
 */
public class RSAUtils{

	/** 加密算法RSA */
    public static final String KEY_ALGORITHM = "RSA";
    
    /**
     * RSA最大加密明文大小
     */
    private static final int MAX_ENCRYPT_BLOCK = 117;
    
    /**
     * RSA最大解密密文大小
     */
    private static final int MAX_DECRYPT_BLOCK = 128;
    
    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCkQEx75k5gY6xZbq7o+oEFL0Xy"
			+"gVWXER13PcJoBXJd4b/Gq/dOKm6coR/nZeuVi6taCvk5VnkPmeZ+cd8ZGo2xQiEf"
			+"x7XuU/PB9n3syoJE3QRdO5YA9j1X1LtrTQFfQ26Nm3jUNRjRAlVLT2oX4JT/C6p4"
			+"T4Lnck50OvASBaIguQIDAQAB";
    public static final String  privatekey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKRATHvmTmBjrFluruj6gQUvRfKBVZcRHXc9wmgFcl3hv8ar904qbpyhH+dl65WLq1oK+TlWeQ+Z5n5x3xkajbFCIR/Hte5T88H2fezKgkTdBF07lgD2PVfUu2tNAV9Dbo2beNQ1GNECVUtPahfglP8LqnhPgudyTnQ68BIFoiC5AgMBAAECgYEAj87MKF7ImJQsPlEuS0Wo2QU1MhwS8fsaI5mO/Uo4RHaevPtnz5/ghuAd3VBAro62Kdq9czESeiRanwAvVYGX5itDrFs0t37OvZc3lmyQY5Ig7vM1ws+MlhYq1J6tQjKBuTtEsVfaFUaK8/wexXmyrk4MnGpTfJnTjpt9jYm3BECQQDZ7q/RD1yEqjZ0pFA+kRB9dXkwvQHfF3u4BnlKlA4XZQIZTLHlqceIAGazF41Ts/ZBTmdFEouSAFdgr/CtORbLAkEAwPEkUkGK2unZzt+2Lgi/KKMQx96IqhX4R48vUGebycON+dReedNy0fY76+DZXX1cqpSxd6zOCbhPomRRp1+yCwJBAL9klBvydbo9El4WADMyi1zjUm+vTnly0kCnztXkeQuqtdEqPgIIvSd/0rHuOTwNjHOGO8O5qcGrcxGC8sfun0kCQGPXJN1vzyOy6SO0/ffaTNkBcLiMfhnNnpmhDXHE+4evqvNBotXVxk/B5IYN500Khv46TY9JG6FJ/+NfmCVNTrsCQGWVlZfsPkLaAPRSOfUKLtK3DAVNYW7ziP4ZKzM3I9kKhNPoOY9r/xc/BJgcwysihjXp9dBY889UhtxjroDyJas=";
	
    /** 生成密钥对(公钥和私钥) */
    public static Map<String, String> genKeyPair() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        Map<String, String> keyMap = new HashMap<String, String>(2);
        Encoder encoder = Base64.getEncoder();
        String publickeyBase64 = encoder.encodeToString(publicKey.getEncoded());
        String privatekeyBase64 = encoder.encodeToString(privateKey.getEncoded());
        
        keyMap.put("RSAPublicKey", publickeyBase64);
        keyMap.put("RSAPrivateKey", privatekeyBase64);
        System.out.println("公钥为:\r\n"+ publickeyBase64);
        System.out.println("私钥为:\r\n"+ privatekeyBase64);
        return keyMap;
    }
    
    /**
     * 私钥解密
     * @param source加密数据（base6编码）
     * @param privateKey 私钥(BASE64编码)
     */
    public static String decryptByPrivateKey(String source, String privateKey)throws Exception {
    	Decoder decoder = Base64.getDecoder();
    	byte[] encryptedData = decoder.decode(source);
        byte[] keyBytes = decoder.decode(privateKey);
        
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateK);
//        byte[] result = cipher.doFinal(encryptedData);
        byte[] result = decryptCore(cipher, encryptedData);
        return new String(result);
    }

    /**
     * 公钥解密
     * @param source加密数据（base6编码）
     * @param publicKey 公钥(BASE64编码)
     */
    public static String decryptByPublicKey(String source, String publicKey)throws Exception {
    	Decoder decoder = Base64.getDecoder();
    	byte[] encryptedData = decoder.decode(source);
        byte[] keyBytes = decoder.decode(publicKey);
        
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicK);
//        byte[] result = cipher.doFinal(encryptedData);
        byte[] result = decryptCore(cipher, encryptedData);
        return new String(result);
    }
    
    /**
     * 解密块
     */
    public static byte[] decryptCore(Cipher cipher,byte[] encryptedData)throws Exception{
         int inputLen = encryptedData.length;
         ByteArrayOutputStream out = new ByteArrayOutputStream();
         int offSet = 0;
         byte[] cache;
         int i = 0;
         // 对数据分段解密
         while (inputLen - offSet > 0) {
             if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
                 cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
             } else {
                 cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
             }
             out.write(cache, 0, cache.length);
             i++;
             offSet = i * MAX_DECRYPT_BLOCK;
         }
         byte[] decryptedData = out.toByteArray();
         out.close();
         return decryptedData;
    }
    
    /**
     * 公钥加密
     * @param source原始数据
     * @param publicKey 公钥(BASE64编码)
     */
    public static String encryptByPublicKey(String source, String publicKey)throws Exception {
    	Encoder encoder = Base64.getEncoder();
    	Decoder decoder = Base64.getDecoder();
    	byte[] keyBytes = decoder.decode(publicKey);
    	// Base64解码
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicK = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicK);
//        byte[] result = cipher.doFinal(source.getBytes());
        byte[] result = encryptCore(cipher, source.getBytes());
        return encoder.encodeToString(result);
    }
    
    /**
     * 私钥加密
     * @param source原始数据
     * @param privateKey 私钥(BASE64编码)
     */
    public static String encryptByPrivateKey(String source, String privateKey)throws Exception {
    	Encoder encoder = Base64.getEncoder();
    	Decoder decoder = Base64.getDecoder();
        byte[] keyBytes = decoder.decode(privateKey);
        
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateK);
//        byte[] result = cipher.doFinal(source.getBytes());
        byte[] result = encryptCore(cipher, source.getBytes());
        return encoder.encodeToString(result);
    }
    
    /**
     * 加密块
     */
    public static byte[] encryptCore(Cipher cipher,byte[] data) throws Exception{
        int inputLen = data.length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offSet = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offSet > 0) {
            if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data, offSet, inputLen - offSet);
            }
            out.write(cache, 0, cache.length);
            i++;
            offSet = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encryptedData = out.toByteArray();
        out.close();
        return encryptedData;
    }
    
    public static void main(String[] args) {
    	try {
	    	System.err.println("公钥加密——私钥解密");
	        String source = "sign=4D349D9236D35B64B698EEC1BF63416C&userName=wjw&password=d88ac035be56893adc167e31bc1";
	        System.out.println("原始数据：\r\n" + source);
	        String encodedData =encryptByPublicKey(source, publicKey);
	        System.out.println("密文数据(base64)：\r\n" + new String(encodedData));
	        String result = decryptByPrivateKey(encodedData, privatekey);
	        System.out.println("解密后数据: \r\n" + result);
	        System.err.println("=======================");
	        System.err.println("私钥加密——公钥解密");
	        System.out.println("原始数据：\r\n" + source);
	        String encodedData2 =encryptByPrivateKey(source, privatekey);
	        System.out.println("密文数据(base64)：\r\n" + new String(encodedData2));
	        String result2 = decryptByPublicKey(encodedData2, publicKey);
	        System.out.println("解密后数据: \r\n" + result2);
    		
    		String s3="Lm1tG94EsoAJ70mrsYrLI5xKJiOunyCZbLrpxG+pHz3NAuhsn21y6X3T0lTyy1a6DSQDuivd2jQdHQ6G4wYaVOONhqzvhjP4/txwy417J2YyyA/nLglcClvQ2oIgLbvODrUcy+q4B7QCkWpWtReR/pe+N2LdPpGbVbPUz+VBUQE2jEgSESZLm+E+1On7GJIIpxzCx6/D6KRFRyhZNWp3ANS0I8mBLEq48NVjV+sqBObCVskWRGqDUXcsnOuaY+EJWat45iSvv5YaOaac/LjYkEQz5YdKUsnX53Znp9sxCIMqNtX+OG661yAa8MhSz66+VRYPYK+qnqltCLoqwRX4Bg==";
		 	String rs3 = decryptByPrivateKey(s3, privatekey);
 	        System.out.println("解密后数据: \r\n" + rs3);
    		
    	} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
}
